<template>
  <view class="login-page">
    <!-- 背景装饰 -->
    <view class="bg-decoration">
      <view class="circle circle-1"></view>
      <view class="circle circle-2"></view>
      <view class="circle circle-3"></view>
    </view>

    <view class="login-container">
      <!-- Logo和标题区域 -->
      <view class="header-section">
        <view class="logo-container">
          <image class="logo" src="/static/logo.png" mode="aspectFit" />
          <view class="logo-glow"></view>
        </view>
        <text class="app-name">智教易购</text>
        <text class="app-slogan">让学习更简单，让知识更有趣</text>
      </view>

      <!-- 登录按钮区域 -->
      <view class="login-section">
        <button 
          class="wechat-login-btn" 
          @click="handleWechatLogin"
          :loading="loading"
          :disabled="loading"
        >
          <view class="btn-content">
            <view class="wechat-icon">
              <text class="icon-text">💬</text>
            </view>
            <text class="btn-text">{{ loading ? '登录中...' : '微信一键登录' }}</text>
          </view>
          <view class="btn-shine"></view>
        </button>
        
        <text class="login-tip">安全快捷，无需注册</text>
      </view>

      <!-- 底部协议 -->
      <view class="footer-section">
        <text class="agreement-text">
          登录即表示同意
          <text class="link" @click="viewAgreement">《用户协议》</text>
          和
          <text class="link" @click="viewPrivacy">《隐私政策》</text>
        </text>
      </view>
    </view>

    <view class="bind-modal" v-if="showBindModal">
      <view class="modal-content">
        <view class="modal-header">
          <text class="modal-title">绑定账号</text>
          <text class="modal-close" @click="closeBindModal">×</text>
        </view>
        
        <view class="modal-body">
          <text class="modal-desc">首次登录需要绑定手机号</text>
          
          <view class="input-group">
            <input 
              class="phone-input" 
              type="number" 
              placeholder="请输入手机号" 
              v-model="bindForm.phone"
              maxlength="11"
            />
          </view>
          
          <view class="input-group">
            <input 
              class="nickname-input" 
              type="text" 
              placeholder="请输入昵称（可选）" 
              v-model="bindForm.nickname"
              maxlength="20"
            />
          </view>
        </view>
        
        <view class="modal-footer">
          <button 
            class="bind-btn" 
            @click="handleBind"
            :loading="bindLoading"
            :disabled="bindLoading || !bindForm.phone"
          >
            确认绑定
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { authAPI } from '../../utils/api.js'
import authManager from '../../utils/auth.js'

const loading = ref(false)
const bindLoading = ref(false)
const showBindModal = ref(false)
const bindForm = reactive({
  phone: '',
  nickname: '',
  provider: '',
  code: ''
})

const handleWechatLogin = async () => {
  if (loading.value) return
  
  loading.value = true
  
  try {
    // 显示加载提示
    uni.showLoading({
      title: '登录中...',
      mask: true
    })
    
    // 每次登录都重新获取code（因为code会过期）
    const loginResult = await uni.login({
      provider: 'weixin'
    })
    
    uni.hideLoading()
    
    if (loginResult.code) {
      console.log('获取到微信code:', loginResult.code, '时间:', new Date().toLocaleTimeString())
      await loginWithCode('weixin-mini', loginResult.code)
    } else {
      console.error('微信登录失败: 未获取到code')
      uni.showToast({
        title: '微信登录失败',
        icon: 'none'
      })
      loading.value = false
    }
  } catch (error) {
    uni.hideLoading()
    console.error('微信登录错误:', error)
    uni.showToast({
      title: '登录失败，请重试',
      icon: 'none'
    })
    loading.value = false
  }
}

// 移除不需要的第三方登录和测试方法

const loginWithCode = async (provider, code) => {
  try {
    // 记录code获取时间，用于调试
    const codeTime = new Date().toLocaleTimeString()
    console.log(`使用code: ${code} (获取时间: ${codeTime})`)
    
    const result = await authAPI.login(provider, code)
    
    if (result.code === '00000') {
      const loginData = result.data
      console.log('登录响应数据:', loginData)
      
      // 检查是否需要绑定
      if (loginData.needBind) {
        console.log('需要绑定账号')
        showBindModal.value = true
        bindForm.provider = provider
        bindForm.code = code
        // 绑定页面显示时，保持loading状态
      } else {
        console.log('直接登录成功')
        handleLoginSuccess(loginData)
        loading.value = false
      }
    } else {
      console.error('登录失败:', result.msg)
      
      // 检查是否是code已使用的错误
      if (result.msg && result.msg.includes('code been used')) {
        uni.showToast({
          title: '授权码已过期，请重新登录',
          icon: 'none'
        })
        // 重新获取code
        if (provider === 'weixin-mini') {
          try {
            const loginResult = await uni.login({
              provider: 'weixin'
            })
            if (loginResult.code) {
              console.log('重新获取微信code:', loginResult.code)
              await loginWithCode(provider, loginResult.code)
              return
            }
          } catch (error) {
            console.error('重新获取微信code失败:', error)
          }
        }
      }
      
      uni.showToast({
        title: result.msg || '登录失败',
        icon: 'none'
      })
      loading.value = false
    }
  } catch (error) {
    console.error('登录请求错误:', error)
    uni.showToast({
      title: '网络错误，请重试',
      icon: 'none'
    })
    loading.value = false
  }
}

const handleBind = async () => {
  if (bindLoading.value || !bindForm.phone) return
  
  bindLoading.value = true
  try {
    // 重新获取微信code用于绑定（因为之前的code可能已过期）
    let freshCode = bindForm.code
    if (bindForm.provider === 'weixin-mini') {
      try {
        console.log('绑定前重新获取微信code...')
        const loginResult = await uni.login({
          provider: 'weixin'
        })
        if (loginResult.code) {
          freshCode = loginResult.code
          console.log('绑定使用新的微信code:', freshCode, '时间:', new Date().toLocaleTimeString())
        } else {
          console.error('重新获取微信code失败: 未获取到code')
        }
      } catch (error) {
        console.error('重新获取微信code失败:', error)
      }
    }
    
    console.log('开始绑定，参数:', {
      provider: bindForm.provider,
      code: freshCode,
      phone: bindForm.phone,
      nickname: bindForm.nickname || '',
      codeTime: new Date().toLocaleTimeString()
    })
    
    const result = await authAPI.bind({
      provider: bindForm.provider,
      code: freshCode,
      phone: bindForm.phone,
      nickname: bindForm.nickname || ''
    })
    
    if (result.code === '00000') {
      handleLoginSuccess(result.data)
    } else {
      uni.showToast({
        title: result.msg || '绑定失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('绑定请求错误:', error)
    uni.showToast({
      title: '网络错误，请重试',
      icon: 'none'
    })
  } finally {
    bindLoading.value = false
  }
}

const handleLoginSuccess = (loginData) => {
  console.log('登录成功，保存数据:', loginData)
  
  // 使用认证管理器保存登录信息
  authManager.saveLoginInfo(loginData)
  
  showBindModal.value = false
  loading.value = false
  
  uni.showToast({
    title: '登录成功',
    icon: 'success'
  })
  
  // 延迟返回，确保数据保存完成
  setTimeout(() => {
    // 返回上一页并强制刷新
    uni.navigateBack({
      delta: 1,
      success: () => {
        // 延迟一下再触发页面刷新
        setTimeout(() => {
          // 通过事件总线通知个人中心页面刷新
          uni.$emit('loginStatusChanged')
        }, 100)
      }
    })
  }, 1500)
}

const closeBindModal = () => {
  showBindModal.value = false
  bindForm.phone = ''
  bindForm.nickname = ''
  loading.value = false
}

// 移除不需要的生成模拟code方法

const viewAgreement = () => {
  uni.showToast({
    title: '用户协议',
    icon: 'none'
  })
}

const viewPrivacy = () => {
  uni.showToast({
    title: '隐私政策',
    icon: 'none'
  })
}
</script>

<style scoped>
.login-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
  overflow: hidden;
}

/* 背景装饰 */
.bg-decoration {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none;
}

.circle {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  animation: float 6s ease-in-out infinite;
}

.circle-1 {
  width: 200rpx;
  height: 200rpx;
  top: 10%;
  right: -50rpx;
  animation-delay: 0s;
}

.circle-2 {
  width: 150rpx;
  height: 150rpx;
  top: 60%;
  left: -30rpx;
  animation-delay: 2s;
}

.circle-3 {
  width: 100rpx;
  height: 100rpx;
  top: 80%;
  right: 20%;
  animation-delay: 4s;
}

@keyframes float {
  0%, 100% { transform: translateY(0px) rotate(0deg); }
  50% { transform: translateY(-20px) rotate(180deg); }
}

.login-container {
  position: relative;
  z-index: 1;
  display: flex;
  flex-direction: column;
  height: 100vh;
  padding: 0 60rpx;
}

/* 头部区域 */
.header-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  text-align: center;
  padding-top: 100rpx;
}

.logo-container {
  position: relative;
  margin-bottom: 40rpx;
}

.logo {
  width: 140rpx;
  height: 140rpx;
  border-radius: 50%;
  box-shadow: 0 20rpx 40rpx rgba(0, 0, 0, 0.3);
}

.logo-glow {
  position: absolute;
  top: -10rpx;
  left: -10rpx;
  right: -10rpx;
  bottom: -10rpx;
  background: linear-gradient(45deg, #ff6b35, #ff8c42, #ff6b35);
  border-radius: 50%;
  opacity: 0.3;
  filter: blur(20rpx);
  animation: glow 2s ease-in-out infinite alternate;
}

@keyframes glow {
  from { opacity: 0.3; transform: scale(1); }
  to { opacity: 0.6; transform: scale(1.1); }
}

.app-name {
  font-size: 56rpx;
  font-weight: bold;
  color: #fff;
  margin-bottom: 20rpx;
  text-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.3);
  letter-spacing: 4rpx;
}

.app-slogan {
  font-size: 32rpx;
  color: rgba(255, 255, 255, 0.9);
  line-height: 1.5;
  text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.2);
}

/* 登录区域 */
.login-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 60rpx 0;
}

.wechat-login-btn {
  position: relative;
  width: 100%;
  height: 120rpx;
  background: linear-gradient(135deg, #07c160, #00d4aa);
  border: none;
  border-radius: 60rpx;
  box-shadow: 0 20rpx 40rpx rgba(7, 193, 96, 0.4);
  overflow: hidden;
  transition: all 0.3s ease;
}

.wechat-login-btn:active {
  transform: translateY(4rpx);
  box-shadow: 0 10rpx 20rpx rgba(7, 193, 96, 0.4);
}

.wechat-login-btn:disabled {
  background: linear-gradient(135deg, #ccc, #ddd);
  box-shadow: none;
  transform: none;
}

.btn-content {
  position: relative;
  z-index: 2;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.wechat-icon {
  width: 60rpx;
  height: 60rpx;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20rpx;
  backdrop-filter: blur(10rpx);
}

.icon-text {
  font-size: 36rpx;
}

.btn-text {
  font-size: 36rpx;
  font-weight: bold;
  color: #fff;
  text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.2);
}

.btn-shine {
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
  animation: shine 3s ease-in-out infinite;
}

@keyframes shine {
  0% { left: -100%; }
  50% { left: 100%; }
  100% { left: 100%; }
}

.login-tip {
  margin-top: 30rpx;
  font-size: 28rpx;
  color: rgba(255, 255, 255, 0.8);
  text-align: center;
}

/* 底部区域 */
.footer-section {
  padding: 40rpx 0;
  text-align: center;
}

.agreement-text {
  font-size: 26rpx;
  color: rgba(255, 255, 255, 0.7);
  line-height: 1.6;
}

.link {
  color: #fff;
  text-decoration: underline;
  font-weight: 500;
}

.bind-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;
  backdrop-filter: blur(10rpx);
}

.modal-content {
  width: 600rpx;
  background: #fff;
  border-radius: 30rpx;
  overflow: hidden;
  box-shadow: 0 40rpx 80rpx rgba(0, 0, 0, 0.3);
  animation: modalSlideIn 0.3s ease-out;
}

@keyframes modalSlideIn {
  from {
    opacity: 0;
    transform: translateY(50rpx) scale(0.9);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 40rpx;
  background: linear-gradient(135deg, #ff6b35, #ff8c42);
  color: #fff;
}

.modal-title {
  font-size: 36rpx;
  font-weight: bold;
}

.modal-close {
  font-size: 48rpx;
  color: rgba(255, 255, 255, 0.8);
  padding: 10rpx;
  border-radius: 50%;
  transition: all 0.3s ease;
}

.modal-close:active {
  background: rgba(255, 255, 255, 0.2);
}

.modal-body {
  padding: 40rpx;
}

.modal-desc {
  font-size: 30rpx;
  color: #666;
  margin-bottom: 40rpx;
  text-align: center;
  line-height: 1.5;
}

.input-group {
  margin-bottom: 30rpx;
}

.phone-input,
.nickname-input {
  width: 100%;
  height: 90rpx;
  border: 2rpx solid #e5e5e5;
  border-radius: 15rpx;
  padding: 0 30rpx;
  font-size: 30rpx;
  box-sizing: border-box;
  transition: all 0.3s ease;
}

.phone-input:focus,
.nickname-input:focus {
  border-color: #ff6b35;
  box-shadow: 0 0 0 4rpx rgba(255, 107, 53, 0.1);
}

.modal-footer {
  padding: 40rpx;
  border-top: 2rpx solid #f5f5f5;
}

.bind-btn {
  width: 100%;
  height: 90rpx;
  background: linear-gradient(135deg, #ff6b35, #ff8c42);
  color: #fff;
  border: none;
  border-radius: 15rpx;
  font-size: 32rpx;
  font-weight: bold;
  box-shadow: 0 10rpx 20rpx rgba(255, 107, 53, 0.3);
  transition: all 0.3s ease;
}

.bind-btn:active {
  transform: translateY(2rpx);
  box-shadow: 0 5rpx 10rpx rgba(255, 107, 53, 0.3);
}

.bind-btn:disabled {
  background: linear-gradient(135deg, #ccc, #ddd);
  box-shadow: none;
  transform: none;
}
</style>
